package com.midea.freecolder;

import java.util.ArrayList;
import java.util.List;

public class ThreadLocalTest {
    //private List<String> messages = Lists.newArrayList();
    private List<String> messages = new ArrayList();

/**
    Java8中ThreadLocal对象提供了一个Lambda构造方式，实现了非常简洁的构造方法：withInitial。
    这个方法采用Lambda方式传入实现了 Supplier 函数接口的参数。
*/
//    public static final ThreadLocal<ThreadLocalTest> holder = ThreadLocal.withInitial(ThreadLocalTest::new);
    public static final ThreadLocal<ThreadLocalTest> holder = ThreadLocal.withInitial(() -> new ThreadLocalTest() );
    //public static final ThreadLocal<ThreadLocalTest> holder = new ThreadLocal<>();

    public static void add(String message) {
        holder.get().messages.add(message);
    }

    public static List<String> clear() {
        List<String> messages = holder.get().messages;
        holder.remove();

        System.out.println("size: " + holder.get().messages.size());
        return messages;
    }

    public static void main(String[] args) {
        holder.set(new ThreadLocalTest());
        ThreadLocalTest.add("一枝花算不算浪漫");
        System.out.println(holder.get().messages);
        ThreadLocalTest.clear();
    }
}